﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using TaobaoERP.Core.Common;
using System.Net;
using System.IO;

namespace TaobaoERP.BusinessTaobao.Common
{
    public class Signature
    {
        private static string code =AppSettings.CERT_CODE;// "fb8e87c0a3f511dd906c8613347b303b";//软件注册时获得,此值为公共帐号HelloWorld（donet）注册的值
        public static string DoSignature(SortedList mySL)
        {
            string sip_sign = string.Empty;

            //签名字段的生成，将CERT CODE和所有接口要传的参数进行组合，再将组装好的字符串进行md5加密后转成16进制后得到一个32位的密文
            StringBuilder apidate = new StringBuilder();
            StringBuilder orgin = new StringBuilder();
            orgin.Append(code); //将安全编码放字符串首位
            //对list里的参数进行拼装，参数名+参数值，按自然排序，即所有参数字母排序
            foreach (DictionaryEntry Item in mySL)
            {
                orgin.Append(Item.Key.ToString());
                if (Item.Value != null)
                {
                    orgin.Append(Item.Value.ToString());
                    apidate.Append(Item.Key+"="+Item.Value+"&");
                }
            }
            
            string tomd5str = orgin.ToString();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            sip_sign = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(tomd5str))).Replace("-", "");//对拼装好的字符串进行md5加密
            return apidate.Append("sip_sign=" + sip_sign).ToString();
        }
        /// <summary>
        /// 获取post数据 并得到Headers数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="Content"></param>
        /// <param name="Headers"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public static string Post(string url, string Content, out string status)
        {
            HttpWebRequest hwr = (System.Net.HttpWebRequest)HttpWebRequest.Create(url);
            hwr.Method = "POST";
            hwr.KeepAlive = true;
            hwr.ContentType = "application/x-www-form-urlencoded";
            Stream newStream = hwr.GetRequestStream();
            //ASCIIEncoding encoding = new ASCIIEncoding();
            System.Text.UTF8Encoding encoding = new UTF8Encoding();
            byte[] postdata = encoding.GetBytes(Content);//所有要传参数拼装
            newStream.Write(postdata, 0, postdata.Length);
            newStream.Close();
            HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse();
            Stream s = hwrs.GetResponseStream();
            status = hwrs.Headers.Get(Constants.HTTP_SIP_STATUS);//获得接口返回状态码
            if (status == "9999")
            {
                using (StreamReader sr = new StreamReader(s, Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
            else if (status == "1004")
            {
                return hwrs.Headers.Get(Constants.HEADER_SIP_ISP_LOGINURL);
            }
            else
            {
                return hwrs.Headers.Get(Constants.HEADER_SIP_ERROR_MESSAGE);
            }
        }
        /// <summary>
        /// 获取淘宝返回值
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public static string GetMessage(String result)
        {
            string messages = "";
            switch (Int32.Parse(result))
            {
                case 1: messages = "您是订购者，免登录成功"; break; //订购者和使用者是有权使用的用户
                case 0: messages = "您是使用者，免登录成功"; break;
                case -1: messages = "免登录失败，错误信息：尚未订购该应用"; break;
                case -2: messages = "免登录失败，错误信息：非法用户"; break;
                case -3: messages = "免登录失败，错误信息：没有订购"; break;
                case -4: messages = "免登录失败，错误信息：订阅了多个，不明确"; break;
                case 1001: messages = "免登录失败，错误信息：签名无效"; break;
                case 1002: messages = "免登录失败，错误信息：请求已过期"; break;
                case 1004: messages = "免登录失败，错误信息：需要绑定用户"; break;
                case 1005: messages = "免登录失败，错误信息：需要提供appid"; break;
                case 1006: messages = "免登录失败，错误信息：需要提供服务名"; break;
                case 1007: messages = "免登录失败，错误信息：需要提供签名"; break;
                case 1008: messages = "免登录失败，错误信息：需要提供时间戳"; break;
                case 1010: messages = "免登录失败，错误信息：无权访问服务"; break;
                case 1011: messages = "免登录失败，错误信息：服务不存在"; break;
                case 1012: messages = "免登录失败，错误信息：需要提供SessionId"; break;
                case 1013: messages = "免登录失败，错误信息：需要提供用户名"; break;
                case 1014: messages = "免登录失败，错误信息：回调服务不存在"; break;
                case 1015: messages = "免登录失败，错误信息：AppKey不存在"; break;
                case 1016: messages = "免登录失败，错误信息：服务次数超过限制"; break;
                case 1017: messages = "免登录失败，错误信息：服务请求过于频繁"; break;
                case 1018: messages = "免登录失败，错误信息：登录请求URL过长"; break;
                case 1019: messages = "免登录失败，错误信息：ISP请求IP非法"; break;
                case 1020: messages = "免登录失败，错误信息：请求参数值长度溢出"; break;
                case 1021: messages = "免登录失败，错误信息：isp处理请求失败"; break;
                default: messages = "免登录失败，错误信息：未知异常"; break;
            }
            return messages;
        }
    }
}
